//package com.xry.test1.service.impl;
//
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.xry.test1.model.GasData;
//import com.xry.test1.service.IHomeService;
//import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.messaging.simp.SimpMessagingTemplate;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Service;
//
//import java.time.LocalDateTime;
//
//@Service
//public class KitchenServiceImpl implements IHomeService {
//    @Autowired
//    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送
//
//    @Autowired
//    private MQTTSubscribe mqttSubscribe; // MQTT 订阅
//
//    private Integer lastMessage = -1; // 记录上一次的消息，避免重复推送
//
//
//    /**
//     * 每秒查询一次 MQTT 数据并推送到前端
//     */
//    @Scheduled(fixedRate = 1000) // 每秒执行一次
//    public void checkAndPushMqttMessage() {
//        try {
//            //mqttSubscribe.subscribeToTopic("kitchenGas"); // 订阅主题
//            String message = mqttSubscribe.waitForMessage(); // 等待消息
//            GasData gasData = new GasData();
//            //int messageInt = Integer.parseInt(message);
//            ObjectMapper objectMapper = new ObjectMapper();
//            JsonNode jsonNode = objectMapper.readTree(message);
//            int messageInt = jsonNode.get("gas").asInt();
//            boolean alarmbell = jsonNode.get("alarmbell").asBoolean();
//
//            // 只有数据发生变化时才推送，避免重复推送相同数据
//            //if (messageInt!=lastMessage) {
//                lastMessage = messageInt;
//                gasData.setConcentration(lastMessage);
//                gasData.setDate(LocalDateTime.now().toString());
//                gasData.setAlarmbell(alarmbell);
//                messagingTemplate.convertAndSend("/topic/gasData",gasDzata);
//                System.out.println("✅  推送 WebSocket 数据：" + gasData);
//            //}
//        } catch (Exception e) {
//            System.out.println("❌ MQTT 获取数据失败gas：" + e.getMessage());
//        }
//    }
//}

package com.xry.test1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xry.test1.dao.GasRepository;
import com.xry.test1.model.GasData;
import com.xry.test1.service.IHomeService;
import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import com.xry.test1.service.MQTTSubscriber.MqttMessageHandler;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import jakarta.annotation.PostConstruct;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class KitchenServiceImpl implements IHomeService, MqttMessageHandler {
    //数据库
    @Autowired
    private GasRepository gasRepository;

    @Autowired
    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送

    @Autowired
    private MQTTSubscribe mqttSubscribe; // MQTT 订阅



    private static final String GAS_TOPIC = "kitchen"; // 只订阅 kitchenGas 主题
    private Integer lastMessage = -1; // 记录上一次的气体浓度，避免重复推送

    @PostConstruct
    public void init() {
        mqttSubscribe.subscribeToTopic(GAS_TOPIC,this);
        //System.out.println("✅ KitchenService 已订阅主题：" + GAS_TOPIC);
    }

    public void handleIncomingMessage(String topic, MqttMessage message) {
        if (!GAS_TOPIC.equals(topic)) {
            return; // 过滤掉非 kitchenGas 的消息
        }

        try {
            String payload = new String(message.getPayload());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(payload);

            int gasConcentration = jsonNode.get("gas").asInt();
            boolean alarmbell = jsonNode.get("alarmbell").asBoolean();

            // 只有当数据发生变化时才推送，避免重复推送相同数据
            //if (gasConcentration != lastMessage) {
                lastMessage = gasConcentration;

                GasData gasData = new GasData();
                gasData.setConcentration(gasConcentration);
                gasData.setAlarmbell(alarmbell);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                gasData.setDate(LocalDateTime.now().format(formatter));


                //mysql
            gasRepository.save(gasData);

                messagingTemplate.convertAndSend("/topic/gasData", gasData);
                System.out.println("推送 WebSocket 数据：" + gasData);
            //}
        } catch (Exception e) {
            System.out.println("gas 解析 MQTT 消息失败：" + e.getMessage());
        }
    }
}

